package proxy;

import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * describe:
 *
 * @author huxingjie
 * @date 2020/04/29
 * @since 4.0
 */
public class CglibProxy {

    public static void main(String[] args) {
        //1 在指定目录下生成动态代理类，我们可以反编译看一下里面到底是一些什么东西
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\java\\java_workapace");
        //创建Enhancer对象，类似于JDK动态代理的Proxy类，下一步就是设置几个参数
        Enhancer enhancer = new Enhancer();
        //设置目标类的字节码文件
        enhancer.setSuperclass(Person.class);
        //设置回调函数
        enhancer.setCallback(new MyMehtodInterceptor());
        //这里的creat方法就是正式创建代理类
        Person person = (Person) enhancer.create();
        //调用代理类的eat方法
        person.sayHello();
        //2
        Person p = (Person) Enhancer.create(Person.class, (MethodInterceptor) (o, method, objects, methodProxy) -> {
            //增强
            System.out.println(LocalDateTime.now());
            Object obj = methodProxy.invokeSuper(o, args);
            return obj;
        });
        p.sayHello();
    }
}

    